<template>
  <div class="app-container">

    <!-- 表头 查询与新增 -->
    <el-row>
      <el-col :span="24">
        <div class="filter-container">
          <el-input placeholder="用户手机" v-model="listQuery.query" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
          <el-input placeholder="用户昵称" v-model="listQuery.nickName" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
          <!--<el-select v-model="listQuery.validFlag" placeholder="有效标志" clearable class="filter-item" style="width: 150px"
                     @change="handleFilter">
            <el-option v-for="(value, key) in statusOptions" :key="key" :label="value+'('+key+')'" :value="key"/>
          </el-select>-->
          <el-date-picker
            class="filter-item"
            v-model="buyTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline"
                     @click="exportReport">导出至美传递
          </el-button>
        </div>
      </el-col>
    </el-row>


    <!-- 表格list -->
    <el-row>
      <el-col :span="24" :gutter="24">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          element-loading-text="Loading"
          border
          fit
          :height="tableHeight"
          style="width: 100%;"
          highlight-current-row>
          <el-table-column align="center" label="序号" width="80">
            <template slot-scope="scope">
              {{ scope.$index }}
            </template>
          </el-table-column>
          <!--<el-table-column label="编号" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
                {{ scope.row.id }}
            </template>
          </el-table-column>-->
          <el-table-column label="用户昵称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.nickName}}
            </template>
          </el-table-column>
          <!--<el-table-column label="分享类型" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.type  |typeFilter}}
            </template>
          </el-table-column>-->

          <el-table-column label="用户手机" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userTel }}
            </template>
          </el-table-column>

          <el-table-column label="分享时间" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{shareTime}}
            </template>
          </el-table-column>
          <!--<el-table-column label="流量总数" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.flowNum }}
            </template>
          </el-table-column>-->
          <el-table-column label="总关注数" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.subNum }}
            </template>
          </el-table-column>
          <el-table-column label="关注未注册数" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.subNotRegNum }}
            </template>
          </el-table-column>
          <el-table-column label="关注并注册数" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.subAndRegNum }}
            </template>
          </el-table-column>

          <el-table-column label="关注未注册占比" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.subNumPer }}
            </template>
          </el-table-column>
          <el-table-column label="关注并注册占比" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.subAndRegNumPer }}
            </template>
          </el-table-column>

          <el-table-column label="累计消费金额" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.bringConsumerNum }}
            </template>
          </el-table-column>
          <el-table-column label="累计获取积分" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.getPoint }}
            </template>
          </el-table-column>
          <el-table-column label="用户注册时间" show-overflow-tooltip style="width: 6%" align="center">
            <template slot-scope="scope">
              {{ scope.row.modifiedTime | timeFilter}}
            </template>
          </el-table-column>
          <el-table-column label="用户名称" show-overflow-tooltip style="width: 10%" align="center">
            <template slot-scope="scope">
              {{ scope.row.userName }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <!--<el-button size="mini" type="primary" @click="handleUpdate(scope.row)">
                编辑
              </el-button>-->
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total"
                    :page.sync="listQuery.pageNum"
                    :limit.sync="listQuery.pageSize"
                    layout="total, sizes, prev, pager, next"
                    style="float:right;"
                    @pagination="fetchData"/>
      </el-col>
    </el-row>


    <!-- 编辑弹窗 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="100px"
        style="">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="编号" label-width="105px" prop="id">
              <el-input v-model="temp.id" :disabled="dialogStatus === 'update'"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户编号" label-width="105px" prop="userId">
              <el-input v-model="temp.userId"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" label-width="105px" prop="type">
              <el-input v-model="temp.type"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" label-width="105px" prop="createTime">
              <el-date-picker
                v-model="temp.createTime"
                type="date"
                placeholder="选择创建时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" label-width="105px" prop="url">
              <el-input v-model="temp.url"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="" label-width="105px" prop="flowNum">
              <el-input type="number" v-model="temp.flowNum"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" label-width="105px" prop="subNum">
              <el-input type="number" v-model="temp.subNum"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="" label-width="105px" prop="subAndRegNum">
              <el-input type="number" v-model="temp.subAndRegNum"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" label-width="105px" prop="bringConsumerNum">
              <el-input v-model="temp.bringConsumerNum"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="" label-width="105px" prop="getPoint">
              <el-input type="number" v-model="temp.getPoint"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import SxShareCostApi from '@/api/manage/SxShareCostApi';
  import waves from '@/directive/waves'; // Waves directive
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
  export default {
    directives: {waves},
    components: {Pagination},
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          2: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      },
      validFilter(status) {
        const statusMap = {
          1: '有效',
          0: '作废'
        }
        return statusMap[status]
      },
      typeFilter(status) {
        const statusMap = {
          1: '分享有礼',
          2: '邀请有礼'
        }
        return statusMap[status]
      },
      timeFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd hh:mm:ss')
        } else {
          return ''
        }
      },
      dateFilter(time) {
        if (time) {
          return new Date(time).Format('yyyy-MM-dd')
        } else {
          return ''
        }
      },
    },
    data() {
      return {
        tableKey: 0,//表格key值
        list: null, //表格对象
        listLoading: true, //表格加载框
        total: 0, //分页总数
        tableHeight: window.innerHeight - 220, //表格高度
        listQuery: { //表格查询对象
          pageNum: 1,
          pageSize: 10,
          type: 2, //至美传递
          query: '',
          nickName: '',
          validFlag: undefined,
          id: ''
        },
        exportUrl: process.env.BASE_API + '/sxShareCost/exportShareExcel', //导出分享有礼url
        buyTime: [],
        temp: {}, //编辑框临时变量
        statusOptions: { //有效无效下拉框
          '1': '有效',
          '0': '作废'
        },
        dialogFormVisible: false, //编辑框显示
        dialogStatus: '', //编辑框更新插入状态
        textMap: { //编辑框标题
          update: '编辑',
          create: '创建'
        },
        rules: { //编辑框校验规则
          sxShareCostName: [{required: true, message: '名称', trigger: 'change'}],
        }
      }
    },
    computed: {
      validSwitch: {
        // getter
        get: function () {
          return this.temp.validFlag === '1'
        },
        // setter
        set: function (newValue) {
          if (newValue) {
            this.temp.validFlag = '1'
          } else {
            this.temp.validFlag = '0'
          }
        }
      },
      shareTime() {
        let time = '',that = this;
        this.buyTime.forEach((item ,i) =>{

          let temp = item;
          time +=temp ;
          if (i < 1) {
            time += "~";
          }
        });
        return time;
      }
    },
    created() {
      let startTime = new Date(new Date().getTime() - 3600 * 1000 * 24 * 7 + 1000).Format('yyyy-MM-dd');
      let endTime = new Date().Format('yyyy-MM-dd') ;
      this.buyTime.push(startTime);
      this.buyTime.push(endTime);
      this.fetchData()
    },
    methods: {
      /**
       * 获取表格数据
       */
      fetchData() {
        let that = this;
        this.listLoading = true
        if (this.buyTime && this.buyTime.length > 0) {
          this.listQuery.times = JSON.stringify(this.buyTime);
        } else {
          this.listQuery.times = null;
        }
        this.$http.all([SxShareCostApi.getPage(this.listQuery)])
          .then(this.$http.spread(function (perms) {
            that.list = perms.rows
            that.total = perms.total
            that.listLoading = false
          }));
      },
      /**
       * 新增弹窗
       */
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 清空弹窗内容
       */
      resetTemp() {
        this.temp = {
          id : '',
          userId : '',
          type : '',
          createTime : '',
          url : '',
          flowNum : '',
          subNum : '',
          subAndRegNum : '',
          bringConsumerNum : '',
          getPoint : '',
          validFlag: '1'
        }
      },

      /**
       * 导出分享邀请按钮
       */
      exportReport() {

        // 创建一个 form
        var form1 = document.createElement("form");
        form1.id = "form1";
        form1.name = "form1";

        // 添加到 body 中
        document.body.appendChild(form1);

        // 创建一个输入
        var input = document.createElement("input");
        // 设置相应参数
        input.type = "text";
        input.name = "query";
        input.value = this.listQuery.query;

        // 创建一个输入
        let input2 = document.createElement("input");
        // 设置相应参数
        input2.type = "text";
        input2.name = "type";
        input2.value = this.listQuery.type;

        // 创建一个输入
        var input1 = document.createElement("input");
        // 设置相应参数
        input1.type = "text";
        input1.name = "times";
        if (this.buyTime && this.buyTime.length > 0) {
          input1.value = JSON.stringify(this.buyTime);
        } else {
          input1.value = null;
        }

        // 将该输入框插入到 form 中
        form1.appendChild(input);
        form1.appendChild(input1);
        form1.appendChild(input2);

        // form 的提交方式
        form1.method = "POST";
        // form 提交路径
        form1.action = this.exportUrl;

        // 对该 form 执行提交
        form1.submit();
        // 删除该 form
        document.body.removeChild(form1);

      },
      /**
       * 确定新增
       */
      createData() {
        let that = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            SxShareCostApi.insert(this.temp).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            })
          }
        })
      },
      /**
       * 编辑弹窗
       */
      handleUpdate(row) {
        this.temp = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      /**
       * 确认编辑
       */
      updateData() {
        let that = this;
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            SxShareCostApi.update(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 1000,
                onClose() {
                  that.fetchData();
                }
              })
            })
          }
        })
      },
      /**
       * 删除操作
       */
      handleDelete(row) {
        let that = this;
        SxShareCostApi.remove({id: row.id}).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose() {
              that.fetchData();
            }
          })
        })
      },
      /**
       * 搜索过滤
       */
      handleFilter() {
        this.listQuery.pageNum = 1
        this.fetchData()
      }
    }
  }
</script>
